<?php
namespace app\api\controller;

use app\api\controller\Base;
use app\api\controller\TokenService;
use think\facade\Config;
use EasyWeChat\Factory;
use think\facade\Db;
use app\member\model\ImsMcMembers;
use app\member\model\ImsEweiShopMember;
use think\Request;
use app\wechat\service\WechatService;
use app\wechat\service\LoginService;
use app\goods\model\ImsEweiShopGoods;
use think\facade\Filesystem;
use EasyWeChat\MiniApp\Application;
use app\order\model\ImsEweiShopOrder;
use app\order\model\ImsEweiShopOrderGoods;

class Login extends Base
{

    public function __construct(Request $request = null)
    {
        if (is_null($request)) {
            $request = request();
        }
        $this->request = $request;
    }
    public function index()
    {
        $code = $this->request->post('code');
        // 验证用户名和密码等登录逻辑
        $user_id = 1111; // 假设用户登录成功后获取到用户ID为1，实际应根据登录验证逻辑获取
        $tokenService = new TokenService();
        $token = $tokenService->generateToken($user_id);
        //$token = "";
        $data = $tokenService->verifyToken($token);
        return json(['token' => $token,'data'=>$data,'code'=>$code]);
    }

    public function codeGetOpenid()
    {

        $code = $this->request->post('code');
        $phonecode = $this->request->post('phonecode');
        $avatarUrl = $this->request->post('avatarUrl');
        $nickname = $this->request->post('nickname');
        $province = $this->request->post('province','省');
        $city = $this->request->post('city','县');
        $phoneNumber = '';

        $nickname = filterWechatNickname($nickname);

        if (empty($nickname)) {
            $nickname = '微信用户';
        }

        if (!$code) {
            return $this->echojson(-1,'缺少必要参数code');
        }

        //配置后期加在env里或者config
        $config_arr = WechatService::getWxconf();
        $config = [
            'app_id' => $config_arr['appid'],
            'secret' => $config_arr['appsecret'],
            'mch_id' => $config_arr['appsecret'],
            'log' => [
                'level' => 'debug',
            ]
        ];

        $app = new Application($config);
        $result = [];
        $api = $app->getClient();
        $api_url = 'https://api.weixin.qq.com/sns/jscode2session';
        // 3. 准备数据
        $deliveryData = [
            "appid" => $config['app_id'],
            "secret" => $config['secret'],
            "js_code" => $code,
            "grant_type" => 'authorization_code'
        ];
        $result = $api->get($api_url, $deliveryData );
        if (isset($result['errcode']) && $result['errcode'] >0) {
            return $this->echojson(-1,'登录失败,请重试！'.$result['errmsg'].'--'.$result['errcode']);
        }else{
            $openid = isset($result['openid'])?$result['openid']:'';
        }

        //有手机号code码时候获取用户手机号
        if ($phonecode) {
            $accessToken = $app->getAccessToken();
            $access_token = $accessToken->getToken(); // string
            $phone_api_url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;
            // 3. 准备数据
            $phoneData = [
                "code" => $phonecode,
            ];
            $phone_result = $api->post($phone_api_url, [
                    'json' => json_encode($phoneData)
                ]
            );
            if (isset($phone_result['errcode']) && $phone_result['errcode'] >0 ) {
                return $this->echojson(-1,'登录失败,请重试！'.$result['errmsg'].'--'.$result['errcode']);
            }else{
                $phoneNumber = isset($phone_result['phone_info']['phoneNumber'])?$phone_result['phone_info']['phoneNumber']:'';
            }
        }

        $smUser = ImsEweiShopMember::mk()->where(['openid'=>$openid])->find();
        if ($smUser && $phoneNumber) {
            ImsMcMembers::mk()->where(['openid'=>$openid])->update(['mobile'=>$phoneNumber]);
            ImsEweiShopMember::mk()->where(['openid'=>$openid])->update(['mobile'=>$phoneNumber]);
        }
        if(empty($smUser)){
            //添加用户
            $mmUser = ImsMcMembers::mk()->where(['openid'=>$openid])->find();
            if (empty($mmUser)) {
                $mmUser = ImsMcMembers::mk()->create([
                    'uniacid'  =>  '2',
                    'email' =>  $openid.'@wx.com',
                    'password'=>md5($openid),
                    'salt'=>md5($openid),
                    'groupid'=>2,
                    'createtime'=>time(),
                    'nickname'=>$nickname,
                    'openid'=>$openid,
                    'mobile'=>$phoneNumber,
                    'avatar'=>$avatarUrl,
                    'resideprovince'=>$province,
                    'residecity'=>$city,
                ]);
                $uid = $mmUser->id;
            }else{
                $uid = $mmUser['id'];
            }
            $smUser = ImsEweiShopMember::mk()->create([
                'uniacid'  =>  '2',
                'uid' =>  $uid,
                'groupid'=>'',
                'openid'=>$openid,
                'mobile'=>$phoneNumber,
                'createtime'=>time(),
                'nickname'=>$nickname,
                'avatar'=>$avatarUrl,
                'province'=>$province,
                'city'=>$city,
                'area'=>'',
            ]);
        }else{
            //临时代码，后续需没用可以删掉
        }
        $smUser = ImsEweiShopMember::mk()->where(['openid'=>$openid])->find();
        if($smUser){
            //生成token
            $tokenService = new TokenService();
            $smUser['token'] =  $tokenService->generateToken($smUser['id']);
            ImsEweiShopMember::mk()->where(['openid'=>$openid])->update(['token'=>$smUser['token']]);
        }else{
            return $this->echojson(-1,'登录失败,请重试！');
        }
        $this->echojson(0,'用户信息',$smUser);
    }

    public function bindPhone(){

        $code = $this->request->post('code');
        if (!$code) {
            return $this->echojson(-1,'缺少必要参数code');
        }
        //配置后期加在env里或者config
        $conf = [
            'app_id' => 'wx1bc92d664de6af1f ',
            'secret' => 'e4d526b120a03944786c584131b13da5',
            'log' => [
                'level' => 'debug',
                //'file'  =>  APP_PATH . '/public/logs/wxMiniProgramLogin.log'
            ]
        ];
        $result = [];
        $applet = Factory::miniProgram($conf);
        $result = $applet->phone_number->getUserPhoneNumber($code);
        if (isset($result['errcode'])) {
            //Log::error('[Login - applet]::小程序登录失败:' . json_encode($wxInfo));
            return $this->echojson(-1,'获取手机号失败！');
        }


        $this->echojson(0,'打印信息',$result);
    }
}
